package com.lincoln.zuul;

import com.alibaba.fastjson.JSONObject;
import com.lincoln.bean.ApiCode;
import com.netflix.zuul.context.RequestContext;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 路由异常
 * @author lincoln
 */
public class RouterException extends RuntimeException {
    public ApiCode apiCode;

    /**
     * 传入apicode
     *
     * @param apiCode
     */
    public RouterException(int apiCode) {
        this.apiCode = ApiCode.findCode(apiCode);
    }

    /**
     * 传入apicode
     *
     * @param apiCode
     */
    public RouterException(ApiCode apiCode) {
        this.apiCode = apiCode;
    }

    public RouterException() {
        this.apiCode = ApiCode.findCode(ApiCode.CHECK_SUM_ERROR);
    }

    @Override
    public String toString() {
        return this.apiCode.getMsg();
    }

    @Override
    public String getMessage() {
        return this.apiCode.getMsg();
    }

    public String getJson() {
        return JSONObject.toJSONString(apiCode);
    }

    public void flushResponse() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out;
        try {
            out = response.getWriter();
            out.append(this.getJson());
            out.flush();
        } catch (Exception e1) {
            try {
                response.sendError(500);
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }
}
